﻿using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using Microsoft.SemanticKernel;

namespace CodeAgent.Function;

public class CodeFunction
{
    /// <summary>
    /// 执行CMD命令
    /// </summary>
    [KernelFunction, Description("执行CMD命令, 并且等待命令执行完成")]
    public async Task<string> ExecuteCommand(string command)
    {
        Console.WriteLine(command);

        var process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = $"/c {command}",
                // 显示窗口，并且将控制台内容输出
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = false,
                // 设置编码
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8
            }
        };

        process.Start();

        await process.WaitForExitAsync();

        var result = await process.StandardOutput.ReadToEndAsync();

        var error = await process.StandardError.ReadToEndAsync();

        process.Close();

        if (string.IsNullOrWhiteSpace(error))
        {
            Console.WriteLine(result);
            return result;
        }

        await Console.Error.WriteLineAsync(error);
        return error;
    }

    /// <summary>
    /// DotNet构建指定目录下的项目
    /// </summary>
    /// <returns></returns>
    public Task<string> BuildDotNetProject(
        [Description("项目路径")] string projectPath)
    {
        return ExecuteCommand($"dotnet build {projectPath}");
    }

    /// <summary>
    /// 获取当前系统基本信息
    /// </summary>
    [KernelFunction, Description("获取当前系统基本信息")]
    public string GetSystemInfo()
    {
        var os = Environment.OSVersion;
        var platform = Environment.OSVersion.Platform;
        var version = Environment.OSVersion.VersionString;
        var processorCount = Environment.ProcessorCount;
        var systemDirectory = Environment.SystemDirectory;
        var userName = Environment.UserName;
        var machineName = Environment.MachineName;
        var userDomainName = Environment.UserDomainName;
        var currentDirectory = Environment.CurrentDirectory;
        var is64BitOperatingSystem = Environment.Is64BitOperatingSystem;
        var is64BitProcess = Environment.Is64BitProcess;

        return @$"
            操作系统：{os}
            平台：{platform}
            版本：{version}
            处理器数量：{processorCount}
            系统目录：{systemDirectory}
            用户名：{userName}
            机器名：{machineName}
            用户域名：{userDomainName}
            当前目录：{currentDirectory}
            是否为64位操作系统：{is64BitOperatingSystem}
            是否为64位进程：{is64BitProcess}
        ";
    }

    /// <summary>
    /// 修改指定的文件的内容
    /// </summary>
    [KernelFunction, Description("修改指定的文件的内容")]
    public async Task ModifyFileContent(string filePath, string content)
    {
        await File.WriteAllTextAsync(filePath, content);
    }

    /// <summary>
    /// 获取指定目录下所有文件
    /// </summary>
    /// <returns></returns>
    [KernelFunction, Description("获取指定目录下所有文件")]
    public string[] GetFilesInDirectory(
        [Description("目录路径")] string directoryPath)
    {
        return Directory.GetFiles(directoryPath);
    }

    /// <summary>
    /// 文件重命名
    /// </summary>
    /// <returns></returns>
    [KernelFunction, Description("文件重命名")]
    public string RenameFile(
        [Description("文件路径")] string filePath,
        [Description("新文件名")] string newFileName)
    {
        File.Move(filePath, Path.Combine(Path.GetDirectoryName(filePath), newFileName));

        return "文件重命名成功";
    }

    /// <summary>
    /// 修改指定的文件 指定行的内容，如果行不存在则添加
    /// </summary>
    [KernelFunction, Description("修改指定的文件 指定行的内容，如果行不存在则添加")]
    public async Task ModifyFileLineContent(string filePath, int lineNumber, string content)
    {
        Console.WriteLine("修改指定的文件 指定行的内容，如果行不存在则添加：{0} {1} {2}", filePath, lineNumber, content);
        var lines = await File.ReadAllLinesAsync(filePath);

        if (lineNumber > lines.Length)
        {
            await File.AppendAllTextAsync(filePath, content);
        }
        else
        {
            lines[lineNumber - 1] = content;
            await File.WriteAllLinesAsync(filePath, lines);
        }
    }

    /// <summary>
    /// 读取指定文件的内容
    /// </summary>
    [KernelFunction, Description("读取指定文件的内容")]
    public async Task<string> ReadFileContent(string filePath)
    {
        Console.WriteLine("读取指定文件的内容：{0}", filePath);
        return await File.ReadAllTextAsync(filePath);
    }

    /// <summary>
    /// 读取指定文件的指定行的内容
    /// </summary>
    [KernelFunction, Description("读取指定文件的指定行的内容")]
    public async Task<string> ReadFileLineContent(string filePath, int lineNumber)
    {
        Console.WriteLine("读取指定文件的指定行的内容：{0} {1}", filePath, lineNumber);
        var lines = await File.ReadAllLinesAsync(filePath);

        if (lineNumber > lines.Length)
        {
            return "行数超出文件行数";
        }

        return lines[lineNumber - 1];
    }
}